<template>
  <div v-if="weatherData" >
    <div class="header-section">
      <h2 class="city-title">{{ weatherData.city }} 天气预报</h2>
      <div class="sub-header">
        <el-tag type="info" effect="dark" round>
          <el-icon><Clock /></el-icon>
          更新时间: {{ weatherData.reporttime }}
        </el-tag>
      </div>
    </div>
    <el-row :gutter="20">
      <el-col :span="6" v-for="(cast, index) in weatherData.casts" :key="index">
        <el-card shadow="hover"
                 :style="{ backgroundImage: `url(${getBackgroundImage(cast)})`, backgroundSize: 'cover', backgroundPosition: 'center' }">
          <template #header>
            <div class="card-header">
              <span>{{ cast.date }} (周{{ cast.week }})</span>
            </div>
          </template>
          <div>
            <p><strong>白天:</strong></p>
            <p :style="{ color: getTemperatureColor(parseInt(cast.daytemp)) }">{{ cast.dayweather }}, {{ cast.daytemp }}°C</p>
            <el-tag effect="dark">{{ cast.daywind }} {{ cast.daypower }}级</el-tag>
          </div>
          <div>
            <p><strong>晚上:</strong></p>
            <p :style="{ color: getTemperatureColor(parseInt(cast.nighttemp)) }">{{ cast.nightweather }}, {{ cast.nighttemp }}°C</p>
            <el-tag effect="dark">{{ cast.nightwind }} {{ cast.nightpower }}级</el-tag>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 左右布局：左侧ECharts图表，右侧输入框与输出 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="8">
        <div id="main" style="width: 100%; height: 400px;"></div>
      </el-col>
      <el-col :span="16">
        <div style="padding-left: 20px;">
          <div class="advice-container">
            <div class="advice-card">
              <h3 class="advice-title">
                <el-icon><Opportunity /></el-icon>
                智能种植建议
              </h3>
              <div class="search-box">
                <el-input
                    v-model="plantName"
                    placeholder="请输入植物名称"
                    clearable
                    class="plant-input"
                    @keyup.enter="fetchPlantingAdvice"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>

                <!-- 图片上传组件 -->
                <el-upload
                    :action="uploadUrl"
                    :on-success="handlePlantImageUpload"
                    :before-upload="beforePlantUpload"
                    :show-file-list="false"
                    class="upload-btn"
                >
                  <el-button type="primary" :icon="Picture" title="上传植物图片" />
                </el-upload>

                <el-button
                    type="primary"
                    :loading="loading"
                    @click="fetchPlantingAdvice"
                    class="search-btn"
                >
                  <template #default>
                    <el-icon><MagicStick /></el-icon>
                    获取建议
                  </template>
                </el-button>
              </div>

              <!-- 图片预览 -->
              <div v-if="plantPictureUrl" class="preview-container">
                <el-image
                    :src="plantPictureUrl"
                    :preview-src-list="[plantPictureUrl]"
                    style="width: 100px; height: 100px; border-radius: 8px;"
                />
                <el-button
                    type="danger"
                    circle
                    :icon="Delete"
                    @click="plantPictureUrl = ''"
                    class="delete-btn"
                />
              </div>

              <pre v-if="plantingAdvice" style="margin-top: 10px; white-space: pre-wrap;">{{ plantingAdvice }}</pre>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
  <div v-else>
    <p>正在加载天气数据...</p>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import { ElMessage, ElCard, ElRow, ElCol, ElTag, ElInput, ElButton, ElUpload, ElImage } from "element-plus";
import { Clock, Opportunity, Search, MagicStick, Picture, Delete } from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import * as echarts from 'echarts';

// 天气图标引入
import duoyun from "@/assets/weather/多云.png";
import qing from "@/assets/weather/晴.png";
import xue from "@/assets/weather/雪.png";
import yu from "@/assets/weather/雨.png";
import feng from "@/assets/weather/风.png";
import lei from "@/assets/weather/雷雨.png";
const baseUrl = import.meta.env.VITE_BASE_URL;

const weatherData = ref(null);
const chartInstance = ref(null);
const plantName = ref('');
const plantPictureUrl = ref('');
const plantingAdvice = ref(null);
const loading = ref(false);

const CACHE_KEY = 'weatherCache';
const CACHE_DURATION = 60 * 60 * 1000;
const CACHE_KEY_ADVICE = 'plantingAdviceCache';
const uploadUrl = `${baseUrl}/files/upload`;
// 天气数据加载
const loadWeather = () => {
  const cachedData = localStorage.getItem(CACHE_KEY);
  if (cachedData) {
    const cache = JSON.parse(cachedData);
    if (cache.timestamp + CACHE_DURATION > Date.now()) {
      weatherData.value = cache.data.forecasts[0];
      return;
    }
  }

  request.get(`/weather/getWeather`).then(res => {
    if (res.code === '200') {
      try {
        const data = JSON.parse(res.data);
        if (data.status === '1' && data.infocode === '10000' && data.forecasts?.length > 0) {
          weatherData.value = data.forecasts[0];
          localStorage.setItem(CACHE_KEY, JSON.stringify({
            timestamp: Date.now(),
            data
          }));
        } else {
          ElMessage.error(data.info || '获取天气数据失败');
        }
      } catch (error) {
        console.error('解析天气数据失败:', error);
        ElMessage.error('解析天气数据失败');
      }
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(error => {
    console.error('请求天气数据失败:', error);
    ElMessage.error('请求天气数据失败');
  });
};

// ECharts图表初始化
const initChart = () => {
  const chartDom = document.getElementById('main');
  if (!chartDom) return;

  chartInstance.value = echarts.init(chartDom);
  if (!weatherData.value?.casts) return;

  const dates = weatherData.value.casts.map(cast => cast.date);
  const dayTemps = weatherData.value.casts.map(cast => parseInt(cast.daytemp));
  const nightTemps = weatherData.value.casts.map(cast => parseInt(cast.nighttemp));

  const option = {
    title: { text: `${weatherData.value.city} 温度变化` },
    tooltip: {
      trigger: 'axis',
      formatter: params => {
        let html = `<strong>${params[0].name}</strong><br/>`;
        params.forEach(param => {
          const cast = weatherData.value.casts[param.dataIndex];
          html += `${param.seriesName}: ${param.value}°C<br/>
                   白天: ${cast.daywind} ${cast.daypower}级<br/>
                   夜晚: ${cast.nightwind} ${cast.nightpower}级`;
        });
        return html;
      }
    },
    xAxis: { type: 'category', data: dates },
    yAxis: { type: 'value', name: '温度 (°C)' },
    series: [
      { name: '白天温度', type: 'line', data: dayTemps, smooth: true },
      { name: '夜晚温度', type: 'line', data: nightTemps, smooth: true }
    ]
  };

  chartInstance.value.setOption(option);
};

// 图片上传处理
const handlePlantImageUpload = (response) => {
  if (response.code === '200') {
    plantPictureUrl.value = response.data;
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(response.msg || '图片上传失败');
  }
};

const beforePlantUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过5MB!");
    return false;
  }
  return true;
};

// 获取种植建议
const fetchPlantingAdvice = () => {
  if (!plantName.value && !plantPictureUrl.value) {
    ElMessage.warning('请输入植物名称或上传图片');
    return;
  }

  loading.value = true;
  request.post('/getPlantingAdvice', {
    plant: plantName.value,
    plantPictureUrl: plantPictureUrl.value
  }).then(res => {
    if (res.code === '200') {
      plantingAdvice.value = res.data;
      localStorage.setItem(CACHE_KEY_ADVICE, JSON.stringify({
        timestamp: Date.now(),
        data: res.data
      }));
    } else {
      ElMessage.error(res.msg || '获取建议失败');
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error('请求种植建议失败');
  }).finally(() => {
    loading.value = false;
  });
};

// 其他辅助函数
const getCurrentHour = () => new Date().getHours();

const weatherIcons = [
  { keyword: '雷', icon: lei },
  { keyword: '雨', icon: yu },
  { keyword: '雪', icon: xue },
  { keyword: '风', icon: feng },
  { keyword: '晴', icon: qing },
  { keyword: '多云', icon: duoyun }
];

const getWeatherIcon = (weatherDesc) =>
    weatherIcons.find(item => weatherDesc.includes(item.keyword))?.icon;

const getBackgroundImage = (cast) => {
  const isDayTime = getCurrentHour() >= 6 && getCurrentHour() < 18;
  return getWeatherIcon(isDayTime ? cast.dayweather : cast.nightweather);
};

const getTemperatureColor = (temp) =>
    temp > 30 ? 'red' : temp < 20 ? 'blue' : 'green';

// 生命周期和监听
watch(weatherData, (newVal) => {
  if (newVal) nextTick(initChart);
});

onMounted(() => {
  loadWeather();
  const cachedAdvice = localStorage.getItem(CACHE_KEY_ADVICE);
  if (cachedAdvice) {
    const { timestamp, data } = JSON.parse(cachedAdvice);
    if (Date.now() - timestamp < CACHE_DURATION) {
      plantingAdvice.value = data;
    }
  }
});
</script>

<style scoped>
.header-section {
  margin-bottom: 32px;
  text-align: center;
}

.city-title {
  font-size: 28px;
  color: #303133;
  margin-bottom: 12px;
  font-weight: 600;
}

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

.plant-input {
  flex: 1;
}

.upload-btn {
  margin-right: 5px;
}

.preview-container {
  position: relative;
  display: inline-block;
  margin-top: 10px;
}

.delete-btn {
  position: absolute;
  right: -10px;
  top: -10px;
  padding: 5px;
  transform: scale(0.8);
}

.advice-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

pre {
  background: #f8f8f8;
  padding: 15px;
  border-radius: 8px;
  font-family: Consolas, Monaco, monospace;
}

@media (max-width: 768px) {
  .search-box {
    flex-wrap: wrap;

    .plant-input {
      width: 100%;
      margin-bottom: 10px;
    }

    .upload-btn, .search-btn {
      flex: 1;
    }
  }
}
</style>
